package com.qining618.common.utils;

import com.qining618.common.exception.BusinessException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.Set;

/**
 * @author flt
 * @date 2019-09-25
 */
public class ValidatordUtil<T> {


    public static <T> void validate(T object,  Class<?>... groups) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> requestViolations = validator.validate(object, groups);
        boolean requestHasViolations = !requestViolations.isEmpty();
        if (requestHasViolations) {
            throw new BusinessException(new ArrayList<>(requestViolations).get(0).getMessage());
        }
    }

}
